#!/usr/bin/env python3
"""
Media Create GUI - Cross-platform Development Environment Setup
跨平台开发环境设置脚本
"""

import os
import sys
import subprocess
import venv
from pathlib import Path
import platform

def check_virtual_environment():
    """检查是否在虚拟环境中"""
    return (
        hasattr(sys, 'real_prefix') or
        (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix) or
        os.getenv('VIRTUAL_ENV') is not None
    )

def get_virtual_env_info():
    """获取虚拟环境信息"""
    if os.getenv('VIRTUAL_ENV'):
        return os.getenv('VIRTUAL_ENV')
    elif hasattr(sys, 'real_prefix'):
        return sys.real_prefix
    elif hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix:
        return sys.prefix
    return None

def run_command(command, description, shell=True):
    """运行命令并检查返回码"""
    print(f"📦 {description}...")
    try:
        result = subprocess.run(
            command, 
            shell=shell, 
            check=True, 
            capture_output=True, 
            text=True
        )
        print(f"✅ {description} - 成功")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ {description} - 失败")
        print(f"错误信息: {e.stderr}")
        return False

def get_python_executable():
    """获取Python可执行文件路径"""
    if platform.system() == "Windows":
        venv_python = Path(".venv") / "Scripts" / "python.exe"
    else:
        venv_python = Path(".venv") / "bin" / "python"
    return venv_python

def create_directories():
    """创建必要的目录"""
    print("\n📁 创建必要的目录...")
    
    directories = [
        "logs",
        "uploads", 
        "generated_content",
        "profiles",
        "temp",
        "alembic/versions"
    ]
    
    for directory in directories:
        dir_path = Path(directory)
        if not dir_path.exists():
            dir_path.mkdir(parents=True, exist_ok=True)
            print(f"✅ 创建目录: {directory}")
    
    return True

def setup_virtual_environment():
    """设置虚拟环境"""
    venv_path = Path(".venv")
    
    if venv_path.exists():
        print("📁 发现现有虚拟环境，跳过创建")
        return True
    
    print("🐍 创建虚拟环境...")
    try:
        venv.create(venv_path, with_pip=True)
        print("✅ 虚拟环境创建成功")
        return True
    except Exception as e:
        print(f"❌ 虚拟环境创建失败: {e}")
        return False

def install_dependencies():
    """安装依赖包"""
    print("\n📚 开始安装依赖包...")
    
    venv_python = get_python_executable()
    
    if not venv_python.exists():
        print("❌ 虚拟环境Python未找到")
        return False
    
    # 升级pip
    if not run_command(f"{venv_python} -m pip install --upgrade pip", "升级pip"):
        return False
    
    # 安装项目依赖
    if not run_command(f"{venv_python} -m pip install -e .", "安装项目依赖"):
        return False
    
    # 安装开发依赖
    if not run_command(f"{venv_python} -m pip install -e .[dev]", "安装开发依赖"):
        return False
    
    return True

def setup_pre_commit():
    """设置pre-commit钩子"""
    print("\n🪝 设置pre-commit钩子...")
    
    venv_python = get_python_executable()
    
    # 检查是否存在.pre-commit-config.yaml
    if not Path(".pre-commit-config.yaml").exists():
        print("⚠️  未找到.pre-commit-config.yaml，跳过pre-commit设置")
        return True
    
    return run_command(f"{venv_python} -m pre_commit install", "安装pre-commit钩子")

def create_env_file():
    """创建环境文件"""
    print("\n⚙️  创建环境配置文件...")
    
    env_example = Path(".env.example")
    env_file = Path(".env")
    
    if env_file.exists():
        print("⚠️  .env文件已存在，跳过创建")
        return True
    
    if not env_example.exists():
        print("❌ 未找到.env.example模板文件")
        return False
    
    try:
        # 复制模板文件
        env_content = env_example.read_text()
        env_file.write_text(env_content)
        
        print("✅ .env文件创建成功")
        print("📝 请编辑 .env 文件，填入实际的配置值")
        return True
    except Exception as e:
        print(f"❌ 创建.env文件失败: {e}")
        return False

def run_safety_checks():
    """运行安全检查"""
    print("\n🔒 运行安全检查...")
    
    # 检查Python版本
    if sys.version_info < (3, 11):
        print(f"❌ Python版本过低，需要3.11+, 当前: {sys.version}")
        return False
    print(f"✅ Python版本检查通过: {sys.version}")
    
    # 检查依赖冲突
    print("🔍 检查依赖冲突...")
    venv_python = get_python_executable()
    result = subprocess.run(
        [str(venv_python), "-m", "pip", "check"],
        capture_output=True,
        text=True
    )
    
    if result.returncode == 0:
        print("✅ 依赖检查通过，无冲突")
    else:
        print("⚠️  发现依赖冲突:")
        print(result.stdout)
    
    return True

def create_activation_script():
    """创建激活脚本"""
    print("\n📝 创建激活脚本...")
    
    if platform.system() == "Windows":
        # Windows激活脚本
        activate_bat = Path("activate_dev.bat")
        activate_content = """@echo off
echo 🚀 激活 Media Create GUI 开发环境
call .venv\\Scripts\\activate.bat
if %errorlevel% equ 0 (
    echo ✅ 开发环境已激活
    echo 📖 可用命令:
    echo   - uvicorn src.media_create.main:app --reload  # 启动开发服务器
    echo   - ruff check src/                           # 代码检查
    echo   - mypy src/                                 # 类型检查
    echo   - pytest                                   # 运行测试
) else (
    echo ❌ 激活失败，请检查虚拟环境
)
"""
    else:
        # Unix激活脚本
        activate_bat = Path("activate_dev.sh")
        activate_content = """#!/bin/bash
echo "🚀 激活 Media Create GUI 开发环境"
source .venv/bin/activate
if [ $? -eq 0 ]; then
    echo "✅ 开发环境已激活"
    echo "📖 可用命令:"
    echo "  - uvicorn src.media_create.main:app --reload  # 启动开发服务器"
    echo "  - ruff check src/                           # 代码检查"
    echo "  - mypy src/                                 # 类型检查"
    echo "  - pytest                                   # 运行测试"
else
    echo "❌ 激活失败，请检查虚拟环境"
fi
"""
    
    activate_bat.write_text(activate_content)
    if platform.system() != "Windows":
        activate_bat.chmod(0o755)
    
    print(f"✅ 激活脚本创建成功: {activate_bat}")
    return True

def main():
    """主函数"""
    print("🚀 Media Create GUI - 跨平台开发环境设置")
    print("=" * 50)
    
    # 检查虚拟环境
    if check_virtual_environment():
        print(f"✅ 已在虚拟环境中: {get_virtual_env_info()}")
    else:
        print("⚠️  未在虚拟环境中，将创建新的虚拟环境")
        if not setup_virtual_environment():
            print("❌ 虚拟环境创建失败，请手动创建")
            sys.exit(1)
        
        # 重新执行脚本在虚拟环境中
        venv_python = get_python_executable()
        if venv_python.exists():
            print(f"🔄 重新启动在虚拟环境中: {venv_python}")
            subprocess.run([str(venv_python), __file__])
            return
        else:
            print("❌ 虚拟环境Python未找到")
            sys.exit(1)
    
    # 创建目录
    if not create_directories():
        print("❌ 目录创建失败")
        sys.exit(1)
    
    # 安装依赖
    if not install_dependencies():
        print("❌ 依赖安装失败")
        sys.exit(1)
    
    # 创建环境文件
    if not create_env_file():
        print("❌ 环境文件创建失败")
        sys.exit(1)
    
    # 设置pre-commit
    setup_pre_commit()
    
    # 安全检查
    if not run_safety_checks():
        print("❌ 安全检查失败")
        sys.exit(1)
    
    # 创建激活脚本
    create_activation_script()
    
    print("\n" + "=" * 50)
    print("🎉 开发环境设置完成！")
    print("\n下一步操作:")
    print("1. 编辑 .env 文件，填入实际的配置值")
    print("2. 设置PostgreSQL数据库")
    print("3. 获取AI模型API密钥")
    print("\n快速开始:")
    if platform.system() == "Windows":
        print("  运行: activate_dev.bat")
    else:
        print("  运行: source activate_dev.sh")
    print("  然后: uvicorn src.media_create.main:app --reload")
    print("\n📖 更多信息请查看 README.md 和 docs/ 目录")

if __name__ == "__main__":
    main()